/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {StyleSheet, Text, View, Dimensions, TouchableOpacity, PixelRatio, TouchableHighlight, Image, NativeModules, Platform, BackHandler, ScrollView, DeviceEventEmitter} from 'react-native';

import AutoHeightWebView from 'react-native-autoheight-webview';

import LinearGradient from 'react-native-linear-gradient';

import {CachedImageBackground,CachedImage} from "react-native-img-cache";

import Common from '../../component/common';

import ToolbarComponent from '../../component/ToolbarComponent';

import Loading from '../../component/loading';

import LoadError from '../../component/loadError';

import Share from '../../component/share';

import ColumnDetailsNext from './columnDetails';

import BriefIntroduction from './briefIntroduction';

import Subscribe from './subscribe';

import Login from '../me/login';

const totalWidth = Dimensions.get('window').width;

const os = Platform.OS;

export default class ColumnDetails extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isRefreshing: false,
      entity: {},
      loading: true,
      success: false,
      errorMessage: '',
      uri: null,
      isBuy: false,
      isCollection: false,
      checkDevice: '',
    };
    this.entity = {};
  }
  componentWillMount(){
    Common.checkDevice((checkDevice) => {
      this.setState({checkDevice});
    });
    if (os === 'android') {
      BackHandler.addEventListener('hardwareBackPress', () => Common.onBack(this,{"id":this.props.did,"type":9,"collectionStatus": this.collection == this.state.isCollection}));
    }
    this.columnDetails = DeviceEventEmitter.addListener('successPay',()=>{
      this.fetchSpecialColumnDetailData();
    });
    this.loginStatus = DeviceEventEmitter.addListener('loginStatus',()=>{
      this.fetchSpecialColumnDetailData();
    });
  this.rememberStyle = DeviceEventEmitter.addListener('styleState',(data)=>{
  	if(data && data.status && this.location && data.id!=this.props.did){
  		this.location.scrollTo({x: 0, y:data.status, animated: false})
  	}
          
  });
 }
  componentDidMount(){
    this.fetchSpecialColumnDetailData();
  }
  componentWillUnmount() {
    this.columnDetails.remove();
    this.loginStatus.remove();
    this.rememberStyle.remove();
    if (os === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', () => Common.onBack(this,{"id":this.props.did,"type":9,"collectionStatus":this.collection == this.state.isCollection}));
    }
  }
  
  fetchSpecialColumnDetailData = () => {
    this.setState({
      loading: true,
      success: false,
    });
    let formData = new FormData();
    formData.append('id',this.props.did);
    if(typeof loginInfo != 'undefined' && loginInfo){
      formData.append('userToken',loginInfo.userToken);
    }
    Common.fetchData("post", "/specialColumn/detail", formData, (responseData) => {
      this.entity = responseData.entity;
      this.setState({loading: false,
                      success: true,
                      isBuy: responseData.entity.isBuy,
                    });
      },() => {
        this.setState({loading: false,
                        success: false,
                        errorMessage: "请求失败",
                      });
      },() => {
        this.setState({loading: false,
                        success: false,
                        errorMessage: "网络错误",
                      });
    });
    Common.isCollection({id:this.props.did, type: 9}, () => {
      this.setState({isCollection: true});
      this.collection = true;
    }, () => {
      this.setState({isCollection: false});
      this.collection = false;
    });
  };
  orderBuy = () =>{
    if(typeof loginInfo != 'undefined' && loginInfo){
      Common.onForward(this, Subscribe, 8, this.entity.parentId,"","no","Normal","false");
    }else{
      Common.onForward(this, Login);
    }
  };
  renderHeader = () => {
    // var showHeight = this.state.isBuy || this.entity.isFree?null : totalWidth * 0.5;
    if(this.entity.lastUpdateTime){
      var date = this.entity.lastUpdateTime.split(' ')[0].split('-');
    }
    var period = Common.toUpper(this.entity.columnNumber);
    var specialColumnNewsContentText = this.entity.specialColumnNewsContentText||"";
    return(
      <View style={styles.specialColumn}>
        {
          this.entity.specialColumnPic2?
          <CachedImage source={{uri: this.entity.specialColumnPic2}} >
          {/*<Image
            ref={(img) => { this.backgroundImage = img; }}
            source={{uri:this.entity.specialColumnPic2}}
            style={styles.absolute}
            onLoadEnd={this.imageLoaded.bind(this)}
          />
          <BlurView
            style={styles.absolute}
            viewRef={this.state.viewRef}
            blurType="dark"
            blurAmount={50}
          />*/}
          <View style={[styles.bigImg, {backgroundColor: 'rgba(0,0,0,0.4)'}]}>
          <View style={styles.userInfo}>
            {this.entity.userPic?
              <CachedImageBackground style={styles.userImg} source={{uri: this.entity.userPic}}/>:
              <Image style={styles.userImg} source={require('../../images/me/User.png')}/>  
            }
            <View style={styles.userLabel}>
              <Text style={styles.userName}>{this.entity.userName}</Text>
              <Text style={styles.userIntroduce}>{this.entity.userRank}</Text>
            </View>
          </View>
          <View style={{backgroundColor: 'transparent'}}>
            <Text style={styles.specialColumnTitle}>第{period}期:</Text>
            <Text style={styles.specialColumnTitle}>{this.entity.specialColumnTitle}</Text>
          </View>
          <Text style={styles.specialColumnPeriod}>{date?(date[1]+"月"+date[2]+"日"):null}更新</Text>
          </View>
        </CachedImage>:
        <Image style={styles.bigImg} source={require('../../images/specialColumn/mistiness.jpg')} >
          <View style={styles.userInfo}>
            {this.entity.userPic?
              <Image style={styles.userImg} source={{uri: this.entity.userPic}}/>:
              <Image style={styles.userImg} source={require('../../images/me/User.png')}/>  
            }
            <View style={styles.userLabel}>
              <Text style={styles.userName}>{this.entity.userName}</Text>
              <Text style={styles.userIntroduce}>{this.entity.userRank}</Text>
            </View>
          </View>
          <View style={{backgroundColor: 'transparent'}}>
            <Text style={styles.specialColumnTitle}>第{period}期:</Text>
            <Text style={styles.specialColumnTitle}>{this.entity.specialColumnTitle}</Text>
          </View>
          <Text style={styles.specialColumnPeriod}>{date?(date[1]+"月"+date[2]+"日"):null}更新</Text>
        </Image>
        }
        
        <View style={styles.specialColumnInfo}>
          <View style={styles.specialColumnInfoIntroduce}>
            <Text style={styles.specialColumnLabel}>本期简介：</Text>
            <Text style={styles.specialColumnLabel}>{this.entity.specialColumnSubject}</Text>
          </View>
        </View>
        <AutoHeightWebView
         style={styles.specialColumnContent}
         source={{ html: "<div style='font-size:16px;color: #494949'>"+specialColumnNewsContentText+"<br></div>"}}
        />
          {this.state.isBuy || this.entity.isFree?
            <View style={[styles.specialColumnFinishSignBox]}>
              <View style={styles.specialColumnFinishSign} />
              <Text style={styles.specialColumnFinishSignL}>本期完</Text>
              <View style={styles.specialColumnFinishSign} />
            </View>:
            <View style={{alignItems: 'center'}}>
              <LinearGradient colors={['rgba(255,255,255, 0.5)', 'rgba(255,255,255, 0.7)', 'rgba(255,255,255, 1)', 'rgba(255,255,255,1)']} style={styles.specialColumnInfoSign}>
                <View style={styles.specialColumnLockSignLine}/>
                <Image style={styles.specialColumnLockSign} source={require('../../images/specialColumn/lock.png')} />
                <View style={styles.specialColumnLockSignLine}/>
              </LinearGradient>
              <View style={styles.specialColumnLockSignBox}>
                <Text style={styles.specialColumnLockLabelText}>阅读完整文章请
                  <Text style={styles.specialColumnLockLabelBuy} onPress={this.orderBuy}>订阅</Text>
                </Text>
              </View>
            </View>
          }
          {
            this.entity.preSpecialColumn.specialColumnTitle || this.entity.nextSpecialColumn.specialColumnTitle?
              <View>
                <View style={styles.specialColumnHandoverBox}>
                  {
                    this.entity.preSpecialColumn.specialColumnTitle?
                      <TouchableHighlight style={{flex: 1}} underlayColor="#fafafa" delayPressIn={100} onPress={() => Common.onForward(this, ColumnDetailsNext, this.entity.preSpecialColumn.specialColumnTitle, this.entity.preSpecialColumn.id,"","no","Normal","true",this.endLocation)}>
                        <View style={[styles.specialColumnHandoverBoxEnter,{paddingLeft:totalWidth*0.05,justifyContent: 'flex-start'}]}>

                          <Image style={styles.specialColumnHandoverBoxEnterPreIcon} source={require('../../images/specialColumn/shang.png')} />
                          <View style={styles.specialColumnHandoverBoxEnterText}>
                            <Text style={styles.specialColumnHandoverBoxEnterLabel}>上一期</Text>
                            <Text style={styles.specialColumnHandoverBoxEnterTitle} numberOfLines={2}>{this.entity.preSpecialColumn.specialColumnTitle}</Text>
                          </View>
                        </View>
                      </TouchableHighlight>:<View style={{flex: 1}} />
                  }
                  {
                    this.entity.nextSpecialColumn.specialColumnTitle?
                      <TouchableHighlight style={{flex: 1}} underlayColor="#fafafa" delayPressIn={100} onPress={() => Common.onForward(this, ColumnDetailsNext, this.entity.nextSpecialColumn.specialColumnTitle, this.entity.nextSpecialColumn.id,"","no","Normal","true",this.endLocation)}>
                        <View style={[styles.specialColumnHandoverBoxEnter,{paddingRight:totalWidth*0.05,justifyContent: 'flex-end'}]}>

                          <View style={styles.specialColumnHandoverBoxEnterText}>
                            <Text style={[styles.specialColumnHandoverBoxEnterLabel,{textAlign:'right'}]}>下一期</Text>
                            <Text style={[styles.specialColumnHandoverBoxEnterTitle,{textAlign: 'right'}]} numberOfLines={2}>{this.entity.nextSpecialColumn.specialColumnTitle}</Text>
                          </View>
                          <Image style={styles.specialColumnHandoverBoxEnterNextIcon} source={require('../../images/specialColumn/xia.png')} />
                        </View>
                      </TouchableHighlight>:<View style={{flex: 1}} />
                  }
                </View>
            </View>:null
        }
        {
        this.entity.relateList.length?
        <Text style={styles.specialColumnRelate}>相关推荐</Text>:null
        }
      </View>
    )
  };
  renderList = () => {
    return(
      this.entity.relateList.length?
      this.entity.relateList.map((val,idx) => {
        return(
          <TouchableHighlight key={idx} style={styles.specialColumnRelateItemTouch} underlayColor="#fafafa" delayPressIn={100} onPress={() => Common.onForward(this, BriefIntroduction, '', val.id,"","no","Normal","true",this.endLocation)}>
            <View style={styles.specialColumnRelateItem}>
              <View style={styles.specialColumnRelateItemLeft}>
                <View style={styles.specialColumnRelateUser} >
                  {val.userPic?
                    <CachedImageBackground style={styles.specialColumnRelateUserImg} source={{uri: val.userPic}} />:
                    <Image style={styles.specialColumnRelateUserImg} source={require('../../images/me/User.png')} />
                  }
                  <View style={styles.specialColumnRelateUserInfo}>
                    <Text style={styles.specialColumnRelateUserName}>{val.userName}</Text>
                    <Text style={styles.specialColumnRelateUserIntroduce}>{val.userRank}</Text>
                  </View>
                </View>
                <View style={styles.specialColumnRelateItemBox}>
                  <Text style={styles.specialColumnRelateItemTitle} numberOfLines={2}>{val.specialColumnTitle}</Text>
                  <Text style={styles.specialColumnRelateItemCon} numberOfLines={2}>{val.specialColumnSubject}</Text>
                </View>
              </View>
              <View style={styles.specialColumnRelateItemRight}>
                {val.specialColumnPic1?
                  <CachedImageBackground style={styles.specialColumnRelateItemCoverImg} source={{uri: val.specialColumnPic1}} />:
                  <View style={[styles.specialColumnRelateItemCoverImg,{borderColor:'#ededed',borderWidth: 1/PixelRatio.get()}]}>
                    <Text style={{color: '#ededed',fontSize: 12}}>暂无图片</Text>
                  </View>
                }
              </View>
            </View>
          </TouchableHighlight>
        );
      }):null
    )
  };
  render() {
    var marginBottom = this.state.isBuy ?0:this.state.checkDevice == 'x'?totalWidth*0.189:totalWidth*0.139;
    var collectionIcon = this.state.isCollection?require("../../images/collection/Collectionon.png"):require("../../images/collection/Collectionoff.png");
    return (
      <View style={styles.container}>
        <ToolbarComponent
          leftItem={{
            title: 'Back',
            layout: 'icon',
            icon: require("../../images/back.png"),
            onPress: () => {
              Common.onBack(this,{"id":this.props.did,"type":9,"collectionStatus":this.collection == this.state.isCollection});
            },
          }}
          extraItem={{
            title: 'Collection',
            layout: 'icon',
            icon: collectionIcon,
            onPress: () => {
              if(this.state.isCollection){
                Common.deleteCollection({id: this.props.did, type: 9},() => {
                  this.setState({isCollection: false});
                });
              }else{
                Common.addCollection({id: this.props.did, type: 9},() => {
                  this.setState({isCollection: true});
                });
              }
            },
          }}
          rightItem={{
            title: 'Share',
            layout: 'icon',
            icon: require("../../images/share/share.png"),
            onPress: () => {
              if(this.refs.share){
                this.refs.share.show(this.locations, this.entity.id,false);
              }
            },
          }}
        >
          <View style={styles.toolbarV}>
            <Text style={styles.toolbarT} numberOfLines={1}>{this.props.name}</Text>
          </View>
        </ToolbarComponent>
        {
        this.state.loading?
          <Loading />:
          (this.state.success?
            <View style={{flex: 1}}>
              <ScrollView ref = {(e) => this.location = e} 
                onScroll ={(event)=>{
                  this.endLocation = event.nativeEvent.contentOffset.y;
                }}
                style={{marginBottom: marginBottom}}>
                <View ref={(e) => this.locations = e} style={{backgroundColor: '#f4f4f4'}}>
                  {this.renderHeader()}
                  {this.renderList()}
                  <View style={{width: totalWidth,height: totalWidth*0.04,backgroundColor: '#f4f4f4'}}/>
                </View>
              </ScrollView>
              {
                this.state.isBuy? null :
                  <View style={styles.bottom}>
                    <LinearGradient colors={['rgba(0,0,0, 0)', 'rgba(19,19,19,0.03)']} style={{width: totalWidth,height: totalWidth*0.015}} />
                    <View style={[styles.bottomCon,this.state.checkDevice == 'x'?{paddingBottom: totalWidth*0.08}:null]}>
                      <View style={styles.bottomLeft}>
                        <Text style={styles.bottomLeftT}>订阅获取更多精彩内容</Text>
                        <Text style={styles.bottomLeftM}>{this.entity.totalColumnMoney}元</Text>
                      </View>
                      <TouchableOpacity style={styles.bottomRight} onPress={this.orderBuy} >
                        <Text style={styles.bottomRightT}>订阅</Text>
                      </TouchableOpacity>
                    </View>
                  </View>
              }
            </View>:<LoadError reload={this.fetchSpecialColumnDetailData} reason={this.state.errorMessage}/>
            )
          }
        <Share ref="share" />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f4f4f4'
  },
  toolbarV: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  toolbarT: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: 20
  },
  specialColumn: {
    flex: 1,
    backgroundColor: '#fff',
  },
  bigImg: {
    width: totalWidth,
    height: totalWidth*0.524,
    paddingHorizontal: totalWidth*0.064,
    paddingBottom: totalWidth*0.048,
    justifyContent: 'space-between',
  },
  userInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: totalWidth*0.034,
    borderColor: '#dbdbdb',
    borderBottomWidth: 2/PixelRatio.get(),
  },
  userImg: {
    width: totalWidth*0.123,
    height: totalWidth*0.123,
    borderRadius: totalWidth*0.0615,
    borderColor: '#fff',
    borderWidth: 1/PixelRatio.get(),
    marginRight: totalWidth*0.045,
  },
  userLabel: {
    flex: 1,
    backgroundColor: 'transparent',
  },
  userName: {
    color: '#fff',
    fontSize: 14,
  },
  userIntroduce: {
    color: '#cbcbcb',
    fontSize: 10,
    lineHeight: Math.round(totalWidth*0.04),
  },
  specialColumnTitle: {
    color: '#fff',
    fontSize: 22,
    fontWeight: 'bold',
  },
  specialColumnPeriod: {
    color: '#e5e5e5',
    fontSize: 10,
    backgroundColor: 'transparent',
  },
  specialColumnInfo: {
    paddingHorizontal: totalWidth*0.05,
    justifyContent: 'center',
  },
  specialColumnContent: {
    paddingHorizontal: totalWidth*0.05,
  },
  specialColumnInfoIntroduce: {
    paddingVertical: totalWidth*0.045,
    paddingHorizontal: totalWidth*0.034,
    borderColor: '#d2d2d2',
    borderBottomWidth: 2/PixelRatio.get(),
  },
  specialColumnLabel: {
    color: '#a3a3a3',
    fontSize: 14,
    lineHeight: Math.round(totalWidth*0.058),
  },
  specialColumnInfoConBox: {
    flex: 1,
  },
  specialColumnInfoCon: {
    paddingVertical: totalWidth*0.045,
  },
  specialColumnInfoSign: {
    position: 'absolute',
    bottom: totalWidth*0.12,
    paddingTop: totalWidth*0.1,
    paddingBottom: totalWidth*0.02,
    width: totalWidth*0.88,
    alignItems: 'center',
    justifyContent: 'space-between',
    alignSelf: 'center',
    flexDirection: 'row',
  },
  specialColumnLockSignLine: {
    borderTopWidth: 2/PixelRatio.get(),
    borderColor: '#adadad',
    width: totalWidth*0.35
  },
  specialColumnLockSign: {
    resizeMode: 'contain',
    width: totalWidth*0.134,
    height: totalWidth*0.096,
  },
  specialColumnFinishSignBox: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    height: totalWidth*0.133,
    marginHorizontal: totalWidth*0.05,
    borderBottomColor: '#d2d2d2',
    borderBottomWidth: 2/PixelRatio.get(),
  },
  specialColumnFinishSign: {
    width: totalWidth*0.05,
    borderTopWidth: 1/PixelRatio.get(),
    borderColor: '#adadad',
  },
  specialColumnFinishSignL: {
    fontSize: 10,
    color: '#adadad',
    width: totalWidth*0.098,
    textAlign: 'center',
    textAlignVertical: 'center',
  },
  specialColumnLockSignBox: {
    width:totalWidth*0.9,
    height: totalWidth*0.12,
    paddingBottom: totalWidth*0.02,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 2/PixelRatio.get(),
    borderBottomColor: '#d2d2d2',
    /*shadowOffset:{  
      width: 0,  
      height: -totalWidth*0.08,  
    },  
    shadowColor: '#fff',  
    shadowOpacity: 0.8, */
  },
  specialColumnLockLabelText: {
    color: '#7d7d7d',
    fontSize: 12,
  },
  specialColumnLockLabelBuy: {
    color: '#fc4442',
  },
  specialColumnHandoverBox: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  specialColumnHandoverBoxEnter: {
    height: totalWidth*0.168,
    flexDirection: 'row',
    alignItems: 'center',
  },
  specialColumnHandoverBoxEnterPreIcon: {
    marginRight: totalWidth*0.077,
  },
  specialColumnHandoverBoxEnterNextIcon: {
    marginLeft: totalWidth*0.077,
  },
  specialColumnHandoverBoxEnterText: {
    width: totalWidth*0.17,
  },
  specialColumnHandoverBoxEnterLabel: {
    color: '#000',
    fontSize: 12,
  },
  specialColumnHandoverBoxEnterTitle: {
    marginTop: 5,
    color: '#787878',
    fontSize: 9,
  },
  specialColumnRelate: {
    paddingHorizontal: totalWidth*0.06,
    paddingVertical: 3,
    color: '#777777',
    fontSize: 10,
    backgroundColor: '#f4f4f4'
  },
  specialColumnRelateItemTouch: {
    backgroundColor: '#fff',
  },
  specialColumnRelateItem: {
    padding: totalWidth*0.038,
    flexDirection: 'row',
    borderBottomWidth: 1/PixelRatio.get(),
    borderColor: '#f3f3f3',
  },
  specialColumnRelateItemLeft: {
    flex: 2,
  },
  specialColumnRelateUser: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingTop: totalWidth*0.004,
    paddingBottom: totalWidth*0.029,
    borderColor: '#d2d2d2',
    borderBottomWidth: 2/PixelRatio.get(),
  },
  specialColumnRelateUserImg: {
    width: totalWidth*0.1,
    height: totalWidth*0.1,
    borderRadius: totalWidth*0.05,
  },
  specialColumnRelateUserInfo: {
    flex: 1,
    marginLeft: 6,
  },
  specialColumnRelateUserName: {
    color: '#000',
    fontSize: 12,
    lineHeight: Math.round(totalWidth*0.054),
  },
  specialColumnRelateUserIntroduce: {
    color: '#939393',
    fontSize: 10,
  },
  specialColumnRelateItemBox: {

  },
  specialColumnRelateItemTitle: {
    color: '#000',
    fontSize: 15,
    lineHeight: Math.round(totalWidth*0.054),
    marginVertical: totalWidth*0.02,
  },
  specialColumnRelateItemCon: {
    color: '#949494',
    fontSize: 10,
    lineHeight: Math.round(totalWidth*0.04),
  },
  specialColumnRelateItemRight: {
    flex: 1,
    alignItems: 'flex-end',
  },
  specialColumnRelateItemCoverImg: {
    width: totalWidth*0.243,
    height: totalWidth*0.328,
    alignItems: 'center',
    justifyContent: 'center',
  },
  bottom: {
    width: totalWidth,
    minHeight: totalWidth*0.133,
    position: 'absolute',
    bottom: 0,
  },
  bottomCon:{
    backgroundColor: '#ffffff',
    paddingHorizontal: totalWidth*0.034,
    paddingVertical: totalWidth*0.03,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  bottomLeft: {
    flex: 1,
  },
  bottomLeftT: {
    fontSize: 12,
    color: '#383838'
  },
  bottomLeftM: {
    fontSize: 10,
    color: '#ff4546',
    marginTop: 3,
  },
  bottomRight: {
    width: totalWidth*0.253,
    height: totalWidth*0.08,
    backgroundColor: '#ff4747',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 2,
  },
  bottomRightT: {
    color: '#fff',
    fontSize: 14,
  },

});